import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { MulterModule } from "@nestjs/platform-express";
import { diskStorage } from "multer";
import { extname } from "path";
import { UploadService } from "./upload.service";
import { UploadController } from "./upload.controller";
import { Upload } from "./entities/upload.entity";
import * as fs from "fs";

// 确保上传目录存在
const uploadDir = "./uploads";
if (!fs.existsSync(uploadDir)) {
	fs.mkdirSync(uploadDir, { recursive: true });
}

@Module({
	imports: [
		TypeOrmModule.forFeature([Upload]),
		MulterModule.register({
			storage: diskStorage({
				destination: "./uploads",
				filename: (req, file, callback) => {
					// 生成唯一文件名
					const uniqueSuffix =
						Date.now() + "-" + Math.round(Math.random() * 1e9);
					const ext = extname(file.originalname);
					const filename = `${uniqueSuffix}${ext}`;
					callback(null, filename);
				},
			}),
			// 限制文件大小为5MB
			limits: {
				fileSize: 5 * 1024 * 1024,
			},
			// 文件过滤
			fileFilter: (req, file, callback) => {
				if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
					return callback(new Error("只允许上传图片文件"), false);
				}
				callback(null, true);
			},
		}),
	],
	controllers: [UploadController],
	providers: [UploadService],
	exports: [UploadService],
})
export class UploadModule {}
